package com.tfswx.jcyw.dmzc.api;

import com.tfswx.jcyw.dmzc.api.dto.LoginInputDTO;
import com.tfswx.jcyw.dmzc.api.dto.LoginOutputDTO;
import com.tfswx.jcyw.dmzc.exception.NotLoginException;
import com.tfswx.jcyw.dmzc.service.DlxxService;
import com.tfswx.swxtool.http.HttpFactory;
import org.apache.commons.lang3.StringUtils;

/**
 * @author 张述江
 * @date 2023/4/4
 */
public class ApiUtil {
    public static final FwdApi fwdApi;

    public static final String base = "192.168.1.29:29090";

    static {
        fwdApi = HttpFactory.builder()
                .base(base)
                .build()
                .beforeReq(httpConfig -> {
                    String url = httpConfig.getUrl();
                    if ("/api/qxgl/login".equals(url)) {
                        return;
                    }
                    String token = getToken();
                    httpConfig.getHeader().put("tf_token", token);
                })
                .create(FwdApi.class);
    }

    private static String getToken() {
        DlxxService dlxx = DlxxService.getInstance();
        if (StringUtils.isBlank(dlxx.getDlbm()) || StringUtils.isBlank(dlxx.getKl())) {
            throw new NotLoginException();
        }
        LoginInputDTO loginInputDTO = new LoginInputDTO();
        loginInputDTO.setDlbm(dlxx.getDlbm());
        loginInputDTO.setKl(dlxx.getKl());
        LoginOutputDTO login = fwdApi.login(loginInputDTO);
        return login.getToken();
    }
}
